<template>
    <div id="inst-info-content">
        <el-tabs type="card" v-model="activePane" closable @tab-remove="removeTab" @tab-click="handleTabClick">
            <!-- <el-tab-pane label="融资买入" name="1">
                <div v-if="activePane == '1'">
                    <FinancingBuysOrder :detail="detail" @reset="reset" />
                </div>
            </el-tab-pane>
            <el-tab-pane label="融券卖出" name="3">
                <div v-if="activePane == '3'">
                    <MarginSellingOrder :detail="detail" @reset="reset" />
                </div>
            </el-tab-pane>
            <el-tab-pane label="担保券买卖" name="4">
                <div v-if="activePane == '4'">
                    <GuaranteeSaleOrder :detail="detail" @reset="reset" />
                </div>
            </el-tab-pane>
            <el-tab-pane label="融资融券申购" name="5">
                <div v-if="activePane == '5'">
                    <MarginSubscriptionOrder :detail="detail" @reset="reset" />
                </div>
            </el-tab-pane> -->
            <el-tab-pane v-for="item in fixedPanes" :label="item.label" :name="item.name" :key="item.key">
                <div id="risk-order-content" class="order-content">
                    <keep-alive>
                        <component :is="item.content" :activePane="activePane" :detail="detail" @reset="reset" @getResult="getResult"></component>
                    </keep-alive>
                    <el-row class="risk-order-bottom" :class="item.class">
                        <h3>
                            <el-row class="result-span">
                                <el-col :span="3">
                                    <span>风控结果:</span>
                                    <status-tag :code="trailResultMsg.riskResult"></status-tag>
                                </el-col>
                                <el-col :span="6">
                                    <span>试算/下单时间: </span>
                                    <span style="color: red">{{ trailResultMsg.calcTime }}</span>
                                </el-col>
                                <el-col :span="5">
                                    <span>计算耗时: </span>
                                    <span style="color: red">{{ trailResultMsg.takeTime }}</span>
                                </el-col>
                                <el-col :span="6">
                                    <span>条目检查数:</span>
                                    <span v-show="trailResultMsg.riskResultTable.length" style="color: red">{{
                                        trailResultMsg.riskResultTable.length
                                    }}</span>
                                </el-col>
                                <el-col :span="4">
                                    <el-button style="float: right" type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                                </el-col>
                            </el-row>
                        </h3>
                        <TrailResult :riskResultTable="trailResultMsg.riskResultTable" :showFieldList="showFieldList" :tableColumns="tableColumns" />
                    </el-row>
                </div>
            </el-tab-pane>
            <el-tab-pane label="指令管理" name="9">
                <InstructionInfo :renderCount="renderCount" @changeTab="changeTab" @handelOperate="handelOperate" />
            </el-tab-pane>
            <el-tab-pane v-for="item in panes" :key="item.key" :name="item.key">
                <span slot="label"><i class="el-icon-discover"></i>{{ item.title }} </span>
                <InstReportDetail :staticResult="staticResult" :history="history" style="padding: 20px"></InstReportDetail>
            </el-tab-pane>
        </el-tabs>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="MARGIN_TRADING_ORDER"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import InstructionInfo from './margin-trading-inst/margin-trading-order-info.vue';
import InstReportDetail from './invest-manage/Inst-report-detail.vue';
import MarginSellingOrder from './margin-trading-inst/margin-selling-order.vue';
import FinancingBuysOrder from './margin-trading-inst/financing-buys-order.vue';
import GuaranteeSaleOrder from './margin-trading-inst/guarantee-sale-order.vue';
import MarginSubscriptionOrder from './margin-trading-inst/margin-subscription-order.vue';
import TrailResult from './components/trail-result.vue';
import StatusTag from '../risk-measure/components/status-tag.vue';
import { getTableLayout } from '@/common/api/commonApi';
import ColumnUtil from './utils/column-util';
import Invest from '@/common/dict/invest';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import SellForRepaymentOrder from './margin-trading-inst/sell-for-repayment-order.vue';
import BuyAndReturnOrder from './margin-trading-inst/buy-and-return-order.vue';
import DirectPayMentOrder from './margin-trading-inst/direct-payment-order.vue';
import DirectCouponPayMentOrder from './margin-trading-inst/direct-coupon-repayment-order.vue';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({
    name: 'marginTradingInst',
    components: {
        InstructionInfo,
        InstReportDetail,
        MarginSellingOrder,
        FinancingBuysOrder,
        GuaranteeSaleOrder,
        MarginSubscriptionOrder,
        SellForRepaymentOrder,
        BuyAndReturnOrder,
        DirectPayMentOrder,
        DirectCouponPayMentOrder,
        TrailResult,
        StatusTag,
        RiskTableLayout,
    },
})
// 融资融券指令
export default class marginTradingInst extends Vue {
    ColumnUtil = new ColumnUtil();
    Invest: any = new Invest();

    // 显示的标签页
    activePane: string = '1';

    // 指令详情
    detail: any = {};
    // 试算结果信息
    trailResultMsg: any = {
        calcTime: '', // 下单/试算时间
        takeTime: '', // 计算耗时
        riskResult: '', // 风控结果
        riskResultTable: [], // 风控结果表数据
    };

    history: boolean = false;

    fixedPanes: any[] = [
        {
            label: '融资买入',
            name: '1',
            content: 'FinancingBuysOrder',
            class: 'bottom1',
        },
        {
            label: '融券卖出',
            name: '2',
            content: 'MarginSellingOrder',
            class: 'bottom2',
        },
        {
            label: '直接还款',
            name: '3',
            content: 'DirectPayMentOrder',
            class: 'bottom3',
        },
        {
            label: '卖券还款',
            name: '4',
            content: 'SellForRepaymentOrder',
            class: 'bottom4',
        },
        {
            label: '直接还券',
            name: '5',
            content: 'DirectCouponPayMentOrder',
            class: 'bottom5',
        },
        {
            label: '买券还券',
            name: '6',
            content: 'BuyAndReturnOrder',
            class: 'bottom6',
        },
        {
            label: '担保券买卖',
            name: '7',
            content: 'GuaranteeSaleOrder',
            class: 'bottom7',
        },
        {
            label: '融资融券申购',
            name: '8',
            content: 'MarginSubscriptionOrder',
            class: 'bottom8',
        },
    ];
    // 所有tabs标签页
    panes: any[] = [];
    staticResult: any = {};
    renderCount: number = 0;
    iconDom: any = null;
    calcLoading: boolean = false;
    tableColumns = this.ColumnUtil.riskTableColumns; // 试算结果表格全部字段

    layoutDialog: boolean = false; // 试算结果表布局设置

    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表

    entryTypeArr: any[] = []; // 风险类型
    ThresholdTypeArr: any[] = []; // 阈值类型
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];
    tableKey: number = 0;
    className: string = 'bottom1';
    orderDirectionPojo: any = {
        '1': '买入',
        '2': '卖出',
        C: '申购',
        '{': '融资买入',
        '[': '融券卖出',
        '}': '卖券还款',
        ']': '买券还券',
    };

    mounted() {
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        this.queryLayout();
    }

    changeTab(val: any) {
        this.detail = val;
        let orderDirectionName: string = '';
        // let orderDirectionMapping = DictionConstUtil.ReversePojo(this.orderDirectionPojo);
        // if (!orderDirectionMapping[this.detail?.orderDirectionName]) {
        //     return '';
        // }
        // this.detail.orderDirection = orderDirectionMapping[this.detail?.orderDirectionName];
        orderDirectionName = this.detail?.orderDirectionName;

        switch (orderDirectionName) {
            case '融资买入':
                this.activePane = '1';
                break;
            case '融券卖出':
                this.activePane = '2';
                break;
            case '直接还款':
                this.activePane = '3';
                break;
            case '卖券还款':
                this.activePane = '4';
                break;
            case '直接还券':
                this.activePane = '5';
                break;
            case '买券还券':
                this.activePane = '6';
                break;
            case '买入' || '卖出':
                this.activePane = '7';
                break;
            case '申购':
                this.activePane = '8';
                break;
            default:
                break;
        }
    }

    reset(val: any) {
        this.detail = val;
    }

    getResult(resMsg: any) {
        this.trailResultMsg = resMsg;
    }

    /* **************************** 布局设置start ***************************** */
    // 获取页面布局信息
    async queryLayout() {
        this.calcLoading = true;
        const resList: any = await new Promise((resolve, reject) => {
            getTableLayout('MARGIN_TRADING_ORDER')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.calcLoading = false;
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        this.showFieldList.forEach((ele: any) => {
            if (['fundCode', 'assetCode', 'fundAccountCode', 'stockCode', 'entryCode'].includes(ele.id)) {
                this.$set(ele, 'sortable', true);
            }
            if (
                [
                    'fundCode',
                    'fundNameSt',
                    'assetCode',
                    'assetName',
                    'fundAccountCode',
                    'fundAccountName',
                    'stockCode',
                    'stockNameSt',
                    'entryCode',
                    'entryName',
                ].includes(ele.id)
            ) {
                this.$set(ele, 'filterMethod', this.filterHandler);
                this.$set(ele, 'filters', [{ data: '' }]);
                this.$set(ele, 'search', true);
            }
            if (ele.id == 'entryType') {
                this.$set(ele, 'filterMethod', this.filterEntryTypeMethod);
                this.$set(ele, 'filters', this.entryTypeArr);
            }
            if (ele.id == 'thresholdType') {
                this.$set(ele, 'filterMethod', this.filterThresholdType);
                this.$set(ele, 'filters', this.ThresholdTypeArr);
            }

            // 重新渲染表格
            this.changeTable();
            this.tableKey++;
        });
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
        this.iconDom = null;
        this.changeTable();
        this.tableKey++;
    }

    changeTable() {
        this.$nextTick(() => {
            const icon = [];
            if (!this.iconDom) {
                const obj = document.querySelector('.' + this.className);
                this.iconDom = obj.querySelectorAll('.vxe-icon--funnel');
                this.iconDom.forEach((ele: any, index) => {
                    if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
                        icon.push(index);
                    }
                });
                for (let i = 0; i < 8; i++) {
                    icon.forEach(ele => {
                        if (ele === i) {
                            this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                        }
                    });
                }
            }
        });
    }

    filterThresholdType({ value, row, column }) {
        return row.thresholdType == value;
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        const list = [];
        for (const key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    /* ************************** 布局设置end *******************************/

    handleTabClick() {
        if (this.activePane !== '9') {
            this.className = 'bottom' + this.activePane;
            this.iconDom = null;
            this.changeTable();
            this.tableKey++;
        } else {
            // 刷新指令管理表格数据
            this.renderCount++;
        }
    }

    handelOperate({ record, history, clickRecord }): void {
        this.history = history;
        let parentRecord = clickRecord;
        let key = String(record.resultId + '-' + record.entryCode);

        for (let i = 0; i < this.panes.length; i++) {
            if (this.panes[i].key === key) {
                this.activePane = key;
                return;
            }
        }
        this.panes.push({ title: key, key: key });
        this.activePane = key;
        this.staticResult = record;
    }

    // 移除tabs
    removeTab(targetKey: string): void {
        let lastIndex;
        this.panes.forEach((pane, i) => {
            if (pane.key === targetKey) {
                lastIndex = i - 1;
            }
        });
        this.panes = this.panes.filter(pane => pane.key !== targetKey);
        if (this.panes.length && this.activePane === targetKey) {
            if (lastIndex >= 0) {
                this.activePane = this.panes[lastIndex].key;
            } else {
                this.activePane = this.panes[0].key;
            }
        }
        if (this.panes.length === 0) {
            this.activePane = '9';
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/inst';
@import '@/pages/risk-time/styles/risk-order';
/deep/ .el-tabs .el-tabs__nav .el-tabs__item:nth-child(-n + 9) .el-icon-close {
    display: none;
}
</style>
